﻿using System.Windows;
using System.Windows.Controls;
using Flux.Editor.Messaging;
using Flux.Editor.Models;
using Flux.Editor.Panes;
using Flux.Editor.ViewModels;
using Xceed.Wpf.AvalonDock;

namespace Flux.Editor
{
	public partial class MainWindow
	{
		public MainWindow()
		{
			InitializeComponent();
			RegisterMessages();
		}

		private void RegisterMessages()
		{
			App.Messenger.Register(Tokens.SwitchUtilityTab, SwitchUtilityTab);
		}
		
		private void DockingManager_OnDocumentClosing(object sender, DocumentClosingEventArgs e)
		{
			var viewModel = (MainWindowViewModel)DataContext;
			viewModel.RemovePane((PaneModel)e.Document.Content);
			viewModel.ActivePane = viewModel.Panes.Count > 0 ? viewModel.Panes[0] : null;
			e.Cancel = true;
		}

		private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
		{
			var viewModel = (MainWindowViewModel)DataContext;
			viewModel.AddPane(PaneTypes.StartPage);
		}

		private void SwitchUtilityTab(object message = null)
		{
			var tabName = (string) message;

			foreach (TabItem tabItem in utilityTabControl.Items)
			{
				if (tabItem.Header.ToString() == tabName)
				{
					tabItem.Focus();
					tabItem.IsSelected = true;
				}
			}
		}
	}
}
